<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] - ".__(($_GET["type"]=="add"? "Add" : "Update")." Member Withdrawal");
$page_title=__(($_GET["type"]=="add"? "Add" : "Update")." Member Withdrawal");
$wit_list_file="withdraw_list.php";

if(!$pv["task"]["Withdrawal"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage member withdrawal."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

if(!in_array($_GET["type"], array("add","edit"))){
	header("location: $this_file?type=add");
	exit();
}

if($_GET["type"]=="edit"){
	if(!$get_s["id"]){
		$errmsg=__("No withdrawal with that ID found!");
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->member_withdraw where id='$get_d[id]'"))){
		$errmsg=__("No withdrawal with that ID found!");
	}else{
		$r_wit=mysql_fetch_assoc($r);
		$r_user = get_user_detail_by_id($r_wit['uid']);
	}
}

if($errmsg){
	$errmsg="<h2>$page_title</h2>".format_err($errmsg);

	print format_admin_page($errmsg, $this_title);
	exit();
}

$r_status=array("pending","paid","cancelled");
$r_status_edit=array("paid","cancelled");
$r_status_add=array("pending","paid");
$r_status_d=array("pending"=>__("Pending Payment"),"paid"=>__("Paid"),"cancelled"=>__("Cancelled"));
$r_payment=array("c","d","e","t","o");
$r_payment_d=array("c"=>__("Cash"), "d"=>__("Cheque"), "e"=>__("Credit Card"), "t"=>__("Telegrapghic Transfer"), "o"=>__("On-hold"));

$td_width=180;
$datetime=ndate($vars["system_date_format"]);

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_user"]){
	$ajresult = ajax_check_user($post_d['uid']);
	$company_id = explode(',', $vars['company_id']);
	if($ajresult['status'] == 3){
		$ajmsg="Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 2){
		$ajmsg="Member ID '$post_s[uid]' is terminated.";
	}elseif(!$pv['task']['View Company Account'] && in_array($ajresult['user_detail']['id'], $company_id)){
		$ajresult['status'] = 3;
		$ajmsg = "Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 1){
		$ajmsg="Member ID: $post_s[uid], Name: {$ajresult['user_detail']['name']}, $vars[ewallet_title]: ".number_format($ajresult['user_detail']['ewallet'], 2).", Bank Account Name: {$ajresult['user_detail']['bank_name']}, Account No.: {$ajresult['user_detail']['bank_acc_no']}";
	}
	
	print format_xml(array('status'=>$ajresult['status'], 'msg'=>$ajmsg));
	exit();
}
//#####END AJAX CALL#####

//#####ADD / EDIT WITHDRAWAL POST#####
if($_POST["__req"]){
	//#####ERROR CHECK#####
	$errmsg=verify_form_data("member_withdraw", $post_s);
	if(!$errmsg){
		if($_GET["type"]=='add'){
			//check user
			if(!$post_s["uid"]){
				$errmsg.=replace_tag(__("'<%field%>' is a required field.")."<br />\n", array("<%field%>"=>__("Member ID")));
			}elseif(!$r_user=get_user_detail_by_id($post_d["uid"])){
				$errmsg.=replace_tag(__("Member ID: '<%uid%>' cannot be found in the database.")."<br />\n", array("<%uid%>"=>$post_s["uid"]));
			}
			//check status
			if(!in_array($post_s["status"], $r_status_add)){
				$errmsg.=__("You have selected an invalid status.")."<br />\n";
			}
			//check ewallet balance
			if(!$errmsg){
				if($post_s["_amount"]>$r_user["ewallet"]){
					$errmsg.=replace_tag(__("The Member ID '<%uid%>' does not have sufficient <%title%>."), array("<%title%>"=>__($vars["ewallet_title"]), "<%uid%>"=>$post_h["uid"]))." ".replace_tag(__("Available: <%x%>"), array("<%x%>"=>number_format($r_user["ewallet"], 2)))." ".replace_tag(__("Requested: <%x%>"), array("<%x%>"=>number_format($post_s["_amount"], 2)))."<br />\n";
				}
			}
		}elseif($_GET["type"]=="edit"){
			//check status
			if($r_wit["status"]=="paid" && !in_array($post_s["status"], $r_status_edit)){
				$errmsg.=__("You have selected an invalid status.")."<br />\n";
			}elseif($r_wit["status"]=="pending" && !in_array($post_s["status"], $r_status)){
				$errmsg.=__("You have selected an invalid status.")."<br />\n";
			}
		}
		if($_GET["type"]=="add" || ($_GET["type"]=="edit" && $r_wit["status"]=="pending")){
			//payment type
			if(!in_array($post_s["payment_type"], $r_payment)){
				$errmsg.=__("You have selected an invalid payment type.")."<br />\n";
			}elseif($post_s["status"]=="paid" && $post_s["payment_type"]=="o"){
				$errmsg.=replace_tag(__("You cannot set the withdrawal status as '<%status1%>' where the payment type is '<%status2%>'."), array("<%status1%>"=>$r_status_d[$post_s["status"]], "<%status2%>"=>$r_payment_d[$post_s["payment_type"]]))."<br />\n";
			}
			//payment date
			if(strlen($post_s["payment_date"]) && !verify_date($post_s["payment_date"])){
				$errmsg.=__("You have provided an invalid payment date.")."<br />\n";
			}
		}
	}
	//#####END ERROR CHECK#####

	//#####ADD TO DB#####
	if(!$errmsg){
		if($post_s["payment_type"]!="o"){
			$payment_date=!$post_s["payment_date"]? $datetime : $post_d["payment_date"];
		}else{
			$payment_date=$post_d["payment_date"];
		}
		if($_GET["type"]=="add"){//add
			if(!mysql_query($sql="update $db->users set ewallet=ewallet-$post_d[_amount] where id='$r_user[id]' limit 1")){
				$errmsg.=__("Error creating a new withdrawal record.")." ".replace_tag(__("The error was due to problem deducting the member's <%title%> account."), array("<%title%>"=>__($vars["ewallet_title"])))."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				$critical_error.="Error creating a new withdrawal record. The error was due to problem deducting the member's $vars[ewallet_title] account.<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
				$critical_error=$errmsg;
			}else{
				if(!mysql_query($ewr_sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$r_user[id]', 'debit', '$post_d[_amount]', '".AddSlashes("Manual withdrawal by $vars[title] staff")."', '$datetime')")){
					$ewrec_errmsg.=replace_tag(__("Error creating the <%title%> transaction record. Please manually record the transaction by executing SQL: <%sql%>"), array("<%title%>"=>__($vars["ewallet_title"]), "<%sql%>"=>$ewr_sql))."<br />\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$r_user[id]' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $post_d['_amount'];
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				$sql="insert into $db->member_withdraw (uid, amount, withdraw_amount, payment_type, acc_name, acc_payee_name, acc_no, acc_swiftcode, acc_branch, payment_date, payment_remark, remark, autowit, status, cdate)
				values ('$r_user[id]', '$post_d[_amount]', '$post_d[_withdraw_amount]', '$post_d[payment_type]', '$post_d[_acc_name]', '$post_d[_acc_payee_name]', '$post_d[_acc_no]', '$post_d[_acc_swiftcode]', '$post_d[_acc_branch]', '$payment_date', '$post_d[_payment_remark]', '$post_d[_remark]', 'n', '$post_d[status]', '$datetime')";
				if(!mysql_query($sql)){
					$errmsg.=__("Error creating a new withdrawal record.")." ".replace_tag(__("The user <%title%> account has been deducted <%x%>, you will need to credit back this amount to this user."), array("<%title%>"=>__($vars["ewallet_title"]), "<%x%>"=>number_format($post_s["_amount"], 2)))."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				}else{
					$new_wid=mysql_insert_id();
				}
			}
			if(!$errmsg){
				$msg=__("The new withdrawal record has been successfully created.")."<br />\n".($ewrec_errmsg? "<br />\n<span class='red'>$ewrec_errmsg</span>" : "");
				$logstr="The new withdrawal record has been successfully created.<br />\n".($ewrec_errmsg? "<br />\n<span class='red'>$ewrec_errmsg</span>" : "");
				if($ewrec_errmsg){
					$critical_error=$msg;
				}
			}else{
				if($ewrec_errmsg){
					$errmsg.=$ewrec_errmsg;
				}
				$critical_error=$errmsg;
			}
		}else{//update
			if($r_wit["status"]=="pending"){
				$sql="update $db->member_withdraw set payment_type='$post_d[payment_type]', payment_date='$payment_date', payment_remark='$post_d[_payment_remark]', remark='$post_d[_remark]', status='$post_d[status]' where id='$get_d[id]' limit 1";
			}elseif($r_wit["status"]=="paid"){
				$sql="update $db->member_withdraw set remark='$post_d[_remark]', status='$post_d[status]' where id='$get_d[id]' limit 1";
			}elseif($r_wit["status"]=="cancelled"){
				$sql="update $db->member_withdraw set remark='$post_d[_remark]' where id='$get_d[id]' limit 1";
			}
			if(!mysql_query($sql)){
				$errmsg.=__("Error updating the withdrawal record.")."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				$critical_error.="Error updating the withdrawal record.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}else{
				if($r_wit["status"]!="cancelled" && $post_s["status"]=="cancelled"){
					if(!mysql_query($sql="update $db->users set ewallet=ewallet+$r_wit[amount] where id='$r_wit[uid]' limit 1")){
						$ew_errmsg.="<br />\n".replace_tag(__("Error crediting back <%x%> <%title%> to the Member ID: <%uid%>, you will need to manually credit back the amount to this member."), array("<%x%>"=>number_format($r_wit["amount"], 2), "<%title%>"=>__($vars["ewallet_title"]), "<%uid%>"=>strval($r_user["id"])))."<br />\n";
						$critical_error.="<br />\nError crediting back ".number_format($r_wit["amount"], 2)." $vars[ewallet_title] to the Member ID: $r_user[id], you will need to manually credit back the amount to this member.<br /><br />SQL: $sql<br /><br />Error: ".mysql_error()."<br />";
					}else{
						if(!mysql_query($ewr_sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$r_wit[uid]', 'credit', '$r_wit[amount]', '".AddSlashes("Withdrawal ID: $get_s[id] cancelled by $vars[title] staff")."', '$datetime')")){
							$ewrec_errmsg.=replace_tag(__("Error creating the <%title%> transaction record. Please manually record the transaction by executing SQL: <%sql%>"), array("<%title%>"=>__($vars["ewallet_title"]), "<%sql%>"=>$ewr_sql))."<br />\n";
							$critical_error.="Error creating the $vars[ewallet_title] transaction record. Please manually record the transaction by executing SQL: $ewr_sql<br /><br />Error: ".mysql_error()."<br />";
						}else{
							$new_eid = mysql_insert_id();
							$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$r_wit[uid]' and id!=$new_eid order by id desc limit 1"), 0);
							if(!$last_bal){
								$last_bal = 0;
							}
							$last_bal += $r_wit['amount'];
							@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
						}
						$ew_msg.="<br />\n".replace_tag(__("The Member ID: <%uid%> has been credited back with <%x%> <%title%>."), array("<%x%>"=>number_format($r_wit["amount"], 2), "<%title%>"=>__($vars["ewallet_title"]), "<%uid%>"=>strval($r_user["id"])))."<br />\n";
					}
				}
			}
			if(!$errmsg){
				$r_wit=mysql_fetch_assoc(mysql_query("select * from $db->member_withdraw where id='$get_d[id]'"));
				$msg=__("The withdrawal record has been successfully updated.")."<br />\n".($ew_errmsg? "<br />\n<span class='red'>$ew_errmsg</span>" : "").($ew_msg? "<br />\n$ew_msg" : "").($ewrec_errmsg? "<br />\n<span class='red'>$ewrec_errmsg</span>" : "");
				if(!$critical_error){
					$logstr="The withdrawal record has been successfully updated.<br />\n"; 
				}else{
					$critical_error="The withdrawal record has been successfully updated.<br />\nHowever, some error occur:<br /><br />$critical_error";
				}
			}elseif($ew_errmsg || $ewrec_errmsg){
				$errmsg.=$ew_errmsg.$ewrec_errmsg;
			}
		}
	}

	//log critical error
	$log_code=$_GET["type"]=="add"? "a-mwa" : "a-mwe";
	$wid = $_GET["type"]=="add"? $new_wid : $get_d['id'];
	if($critical_error){
		$affected_uid=$r_user['id'];
		//log_activity('e', 'a', $aid, 'u', $affected_uid, $log_code, $critical_error, array("wid"=>$wid));
	}elseif($logstr){
		//log_activity('a', 'a', $aid, 'u', $affected_uid, $log_code, $logstr, array("wid"=>$wid));
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err(__("We have encountered some error(s):")."<br />\n<br />\n$errmsg") : "";
}
//#####END WITHDRAW POST#####

$form_fields=array("uid"=>"","_amount"=>"","_withdraw_amount"=>"","payment_type"=>"o","_acc_name"=>"","_acc_payee_name"=>"","_acc_no"=>"","_acc_swiftcode"=>"","_acc_branch"=>"","payment_date"=>"","_payment_remark"=>"","_remark"=>"","status"=>"pending");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=(!$posting? ($_GET["type"]=="edit"? $r_wit[$db_fieldname] : $default) : $post_h[$field]);
}
$dis['uid'] = ($GET['type'] == 'add'? $dis['uid'] : ($posting? $dis['uid'] : $r_user['id']));
$dis["payment_date"]=$dis["payment_date"]=="0000-00-00 00:00:00"? "" : $dis["payment_date"];
$payment_select=($_GET["type"]=="add" || ($_GET["type"]=="edit" && $r_wit["status"]=="pending")? build_select($r_payment, $r_payment_d, $dis["payment_type"], "payment_type", $inputbox_style) : $r_payment_d[$r_wit["payment_type"]]);
$status_select=($_GET["type"]=="add"? build_select($r_status_add, $r_status_d, $dis["status"], "status", $inputbox_style) : ($r_wit["status"]=="pending"? build_select($r_status, $r_status_d, $dis["status"], "status", $inputbox_style) : ($r_wit["status"]=="paid"? build_select($r_status_edit, $r_status_d, $dis["status"], "status", $inputbox_style) : $r_status_d[$r_wit["status"]])));

//user id
if($dis["uid"]){
	if($r=get_user_detail_by_id($dis["uid"])){
		$user_text="<span class='bold'>".replace_tag(__("Member ID: <%uid%>, Name: <%name%>"), array("<%uid%>"=>$dis["uid"], "<%name%>"=>$r["name"]))."<br />\n".
		__($vars["ewallet_title"]).__(":")." ".number_format($r["ewallet"], 2)."<br />\n".
		replace_tag(__("Bank Account Name: <%acc_name%>, Payee Name: <%payee_name%>, Account No.: <%acc_no%>"), array("<%acc_name%>"=>$r["bank_name"], "<%payee_name%>"=>$r["bank_payee_name"], "<%acc_no%>"=>$r["bank_acc_no"]))."</span>";
	}else{
		$user_text="<span class='red'>".__("Invalid Member ID")."</span>";
	}
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=wit_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });

 j('input#check_user_btn').click(function(){
  j('span#user_text').html('').removeClass('red');
  if(j('input[@name=uid]').val()==''){
   j('span#user_text').html('".AddSlashes(__("Please provide a Member ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_user=1',
    data: {'uid': j('input[@name=uid]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('span#user_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+'<br/>';
      });
     }
     var status=j(data).find('status').text();
     j('span#user_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_user_btn').attr('disabled','');
    }
   });
  }
 });
});
</script>";

//back button
$url_referer=$_SERVER["HTTP_REFERER"];
if($post_s["back_url"]){
	$back_url=$post_s["back_url"];
}elseif($url_referer && !strstr($url_referer, $this_file)){
	$back_url=$url_referer;
}else{
	$back_url=$wit_list_file;
}

$display_fields=array("uid","_amount","_withdraw_amount","_acc_name","_acc_payee_name","_acc_no","_acc_swiftcode","_acc_branch","payment_date","_payment_remark","_remark");
foreach($form_fields as $field => $default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["member_withdraw"][$db_fieldname]);
  $readonly=$textarea=false;
  if($field=='uid'){
   if($_GET["type"]=="edit"){
    $readonly=true;
   }else{
    $extra_display="<br />\n<span id='user_text'>$user_text</span> <input type='button' value=\"".__("Check Member")."\" id='check_user_btn' />";
   }
  }elseif($field=='payment_date'){
   $extra_display="<br />\n".replace_tag(__("If you wish to use the current date and time, leave this field empty. The system will only record the
   current date and time if this field is empty AND the payment type is NOT '<%type%>'."), array("<%type%>"=>$r_payment_d["o"])).
   __("Date Format")." YYYY-MM-DD HH:MM:SS";
  }else{
   $extra_display='';
  }
  if($_GET["type"]=="edit"){
   if($r_wit["status"]=="pending" && in_array($field, array("_amount","_acc_name","_acc_payee_name","_acc_no"))){
    $readonly=true;
   }elseif($r_wit["status"]!="pending" && !in_array($field, array("_remark"))) {
    $readonly=true;
   }
  }
  if(in_array($db_fieldname, array("payment_remark","remark"))){
   $textarea=true;
  }
  $readonly_str=$readonly? "readonly='readonly'" : "";
  $form_inputfield[$db_fieldname]="
  <tr>
   <td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
   <td>".($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
  </tr>";
 }
}

$manage_wit=($errmsg || $msg?
"$errmsg $msg" : "")."
<form name='wit_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='back_url' value=\"$back_url\" />
<table class='amt_table'>
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value='".__("Back")."' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".__(($_GET["type"]=="edit"? "Update" : "Add")." Withdrawal")."\" />
  </td>
 </tr>
 <tr class='amt_header'>
  <td colspan='2'>".__("Withdrawal Information")."</td>
 </tr>".($_GET["type"]=="edit"? "
 <tr>
  <td width='$td_width'>".__("Withdrawal ID").__(":")."</td>
  <td>$get_s[id]</td>
 </tr>" : "")."
 $form_inputfield[uid]
 $form_inputfield[amount]  $form_inputfield[withdraw_amount]
 $form_inputfield[acc_name]
 $form_inputfield[acc_swiftcode]
 $form_inputfield[acc_branch]
 $form_inputfield[acc_payee_name]
 $form_inputfield[acc_no]
 <tr>
  <td>".__("Payment Type").__(":")." ".__("*")."</td>
  <td>$payment_select</td>
 </tr>
 $form_inputfield[payment_date]
 $form_inputfield[payment_remark]
 $form_inputfield[remark]
 <tr>
  <td>".__("Status").__(":")." ".__("*")."</td>
  <td>$status_select</td>
 </tr>
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value='".__("Back")."' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".__(($_GET["type"]=="edit"? "Update" : "Add")." Withdrawal")."\" />
  </td>
 </tr>
</table>";

$content="<h2>$page_title</h2>$manage_wit";

print format_admin_page($content, $this_title, $jvscript);
?>